import { Button, Modal, Spin } from 'ant-design-vue'
import { defineComponent, h, ref, toRefs, unref } from 'vue'
import { Card, UploadDragger, Space, message } from 'ant-design-vue'
import { CloudUploadOutlined } from '@ant-design/icons-vue'
import { useBaseSetting } from '@/hooks/setting/useBaseSetting'
import { importTemplate, importUser } from '@/api/system/user'

const ImportUser = defineComponent({
  name: 'ImportUser',
  props: {
    userCode: {
      type: [String],
      required: false
    },
    username: {
      type: [String],
      required: false
    },
    show: {
      type: Boolean
    }
  },
  emits: ['cancelModal', 'confirmModal'],
  setup(props, ctx) {
    const { getThemeColor } = useBaseSetting()
    const loading = ref(false) // 控制遮罩显示状态
    const handleCancel = () => {
      ctx.emit('cancelModal')
    }

    // 自定义上传逻辑，处理文件上传到后端的操作
    const customRequest = async ({ file }) => {
      const formData = new FormData()
      formData.append('file', file)
      loading.value = true // 显示遮罩
      try {
        const response = await importUser(formData)
        // 上传成功后的处理逻辑
        message.success('上传成功!')
        console.log('服务器返回的数据:', response)
        uploadResult(response)
      } catch (error) {
        // 上传失败的处理逻辑
        message.error('上传失败!')
        console.error('上传错误:', error)
        uploadResult('上传失败')
      } finally {
        loading.value = false // 隐藏遮罩
      }
    }

    const uploadResult = (result: string) => {
      Modal.success({
        title: '导入结果',
        content: h('div', { innerHTML: result }),
        onOk() {
          handleCancel()
        }
      })
    }

    const beforeUpload = (file: File) => {
      if (!/\.(xlsx|xls|csv)$/.test(file.name)) {
        message.warning('Excel文件只支持.xlsx, .xls, .csv格式!')
        return
      }
      const isLimit1M = file.size / 1024 / 1024 < 10
      if (!isLimit1M) {
        message.warning('上传的Excel文件大小不能超过10M!')
        return
      }
    }

    const downloadTemplate = () => {
      importTemplate()
        .then((res: any) => {
          const blob = new Blob([res.data], { type: 'application/xlsx' })
          const filename = window.decodeURI(res.headers['content-disposition'].split('=')[1])
          const url = window.URL.createObjectURL(blob)
          const link = document.createElement('a')
          link.href = url
          link.download = filename
          link.click()
          URL.revokeObjectURL(url)
          message.success('模板下载成功')
        })
        .catch(function (error: any) {
          console.log(error)
        })
    }
    return {
      ...toRefs(props),
      getThemeColor,
      loading,
      handleCancel,
      downloadTemplate,
      beforeUpload,
      customRequest
    }
  },
  render() {
    const { show, getThemeColor, loading, customRequest, handleCancel, downloadTemplate, beforeUpload } = this
    return (
      <Modal open={show} title='批量导入' width='600px' footer={null} onCancel={handleCancel}>
        <Card>
          <Space direction='vertical' size={16} style={{ width: '100%' }}>
            <UploadDragger
              ref='uploadExcel'
              accept='.xlsx, .xls, .csv'
              showUploadList={false}
              maxCount={1}
              beforeUpload={beforeUpload}
              customRequest={customRequest}
            >
              <p class='ant-upload-drag-icon' style='margin-bottom: 0;'>
                <CloudUploadOutlined />
              </p>
              <p>
                将Excel文件拖到此处, 或<span style={{ color: unref(getThemeColor) }}>点击上传</span>
              </p>
            </UploadDragger>
          </Space>
          <Space style={{ marginTop: '20px' }}>
            <span>*.xlsx / *.xls</span>
            <Button type={'link'} onClick={downloadTemplate}>
              {'下载模板'}
            </Button>
          </Space>
        </Card>
        {loading && (
          <Spin tip='文件上传中...'>
            <div
              style={{
                position: 'fixed',
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                backgroundColor: 'rgba(0, 0, 0, 0.3)',
                zIndex: 1000
              }}
            ></div>
          </Spin>
        )}
      </Modal>
    )
  }
})
export default ImportUser
